package com.ruoyi.pay.service;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.pay.domain.SysConfigALI;
import com.ruoyi.pay.mapper.SysConfigALiMapper;
import com.ruoyi.pay.utils.DBApplicationConfig;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 系统配置表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2020-07-29
 */
@Service
public class SysConfigService implements ISysConfigService{


    @Resource
    private SysConfigALiMapper sysConfigALiMapper;

    /**
     * 数据库application配置参数
     **/
    private static final MutablePair<String, DBApplicationConfig> APPLICATION_CONFIG = new MutablePair<>("applicationConfig", null);

    public synchronized void initDBConfig(String groupKey) {

        if(APPLICATION_CONFIG.getLeft().equalsIgnoreCase(groupKey)){
            APPLICATION_CONFIG.right = this.selectByGroupKey(groupKey).toJavaObject(DBApplicationConfig.class);
        }
    }


    /**
     * <简述>查询商户系统配置
     * <详细描述>
     * @author syf
     * @date 2024/10/23 11:35
     * @return com.ruoyi.alipay.utils.DBApplicationConfig
     */
    @Override
    public DBApplicationConfig getDBApplicationConfig() {

        // 查询DB
            return this.selectByGroupKey(APPLICATION_CONFIG.getLeft()).toJavaObject(DBApplicationConfig.class);
    }


    /** 根据分组查询，并返回JSON对象格式的数据 **/
    public JSONObject selectByGroupKey(String groupKey){
        JSONObject result = new JSONObject();

        sysConfigALiMapper.selectList(
            SysConfigALI.gw().select(SysConfigALI::getConfigKey, SysConfigALI::getConfigVal).eq(SysConfigALI::getGroupKey, groupKey)
            )
        .stream().forEach(item -> result.put(item.getConfigKey(), item.getConfigVal()));
        return result;
    }


    public int updateByConfigKey(Map<String, String> updateMap) {
        int count = 0;
        Set<String> set = updateMap.keySet();
        for(String k : set) {
            SysConfigALI sysConfig = new SysConfigALI();
            sysConfig.setConfigKey(k);
            sysConfig.setConfigVal(updateMap.get(k));
            boolean update = sysConfigALiMapper.insertOrUpdate(sysConfig);
            if (update) {
                count ++;
            }
        }
        return count;
    }
}
